package com.cxx.autoconfigure.interceptor;

import com.cxx.autoconfigure.constant.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 安全拦截器 可以实现请求限流等功能
 */
public class SecurityInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(SecurityInterceptor.class);

    private static final ConcurrentHashMap<String, Queue<Long>> requestCache = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return checkRateLimit(request, response);
    }

    /**
     * 请求限流 限制在 MAX_REQUESTS_PER_SECOND次/TIME_WINDOW_MS毫秒
     * @param request  请求
     * @param response 响应
     * @return 是否继续
     * @throws IOException 异常
     */
    private boolean checkRateLimit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String clientIp = request.getRemoteAddr();

        // 获取或创建请求时间戳队列
        Queue<Long> requestTimestamps = requestCache.computeIfAbsent(clientIp, k -> new LinkedList<>());

        // 清除过期的请求（超过 1 秒）
        long currentTime = System.currentTimeMillis();
        while (!requestTimestamps.isEmpty() && currentTime - requestTimestamps.peek() > Constants.TIME_WINDOW_MS) {
            requestTimestamps.poll();
        }

        // 检查当前时间窗口内的请求数
        if (requestTimestamps.size() >= Constants.MAX_REQUESTS_PER_SECOND) {
            // 超过限制，返回 429 Too Many Requests
            response.setStatus(429);
            response.getWriter().write("Too many requests. Please try again later.");
            logger.error("<SecuritySummary> {} has too many requests!", clientIp);
            return false;
        }

        // 记录当前请求的时间戳
        requestTimestamps.offer(currentTime);

        return true;
    }
}
